﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TracNghiem.Models;
using System.Text;

namespace TracNghiem.Controllers
{
    public class Test_ServiceController : Controller
    {
       
        // GET: /Test_Service/
        Test_ServiceModel Test_ServiceModel = new Test_ServiceModel();
        Test_QuestionDetailModel Test_QuestionDetailModel = new Test_QuestionDetailModel();
        //public static List<Test_QuestionModel> ts_global { get; set; }
        //public static string is_pattern { get; set; }
        //public static string thoi_gian { get; set; }
        public ActionResult Index(int id)
        {
            ViewBag.menu = xulymenu();
            List<Test_ServiceModel> ts = Test_ServiceModel.getTestByDichvu(id);
            return View(ts);           

        }

        [HttpPost]
        public FileContentResult createDoc()
        {
            string html = Request.Form["html"];
            StringBuilder doc = new StringBuilder();
            doc.Append("<html><body>");
            doc.Append(html);
            doc.Append("</html></body>");

            byte[] buffer = Encoding.Unicode.GetPreamble()
            .Concat(Encoding.Unicode.GetBytes(doc.ToString()))
            .ToArray();

            FileContentResult result = new FileContentResult(buffer, "application/msword");
            string ten_file = "";
            if (Session["user_id"] != null)
            {
                ten_file = Session["user_name"].ToString();
            }
            result.FileDownloadName = string.Format("{0}.doc", ten_file);
            return result;
        }
        public ActionResult Index2()
        {
            ViewBag.menu = xulymenu();
            List<Test_ServiceModel> ts = Test_ServiceModel.getTestByDichvuAll();
            return View(ts);
        }
        public ActionResult home()
        {
            ViewBag.menu = xulymenu();
            return View();
        }
        public ActionResult Detail(int id)
        {
            try
            {
                ViewBag.menu = xulymenu();
                Test_ServiceModel ts = Test_ServiceModel.getTest().Find(delegate(Test_ServiceModel s) { return s.id == id.ToString(); });
                Session["thoi_gian"] = ts.thoi_gian;
                Session["is_pattern"] = ts.is_pattern;

                int tong_so_cau = 0;
                if (ts.is_pattern == "0")
                {
                    List<Test_QuestionDetailModel> test_QuestionDetail = Test_QuestionDetailModel.getTest_QuestionDetail(id.ToString());
                    for (int i = 0; i < test_QuestionDetail.ToArray().Length; i++)
                    {
                        tong_so_cau += Convert.ToInt32(test_QuestionDetail[i].so_cau);
                    }
                    @ViewBag.tong_so_cau = tong_so_cau;
                }
                else
                {
                    TracNghiem.Areas.Admin.Models.Test_PatternModel Test_PatternModel = new TracNghiem.Areas.Admin.Models.Test_PatternModel();
                    List<TracNghiem.Areas.Admin.Models.Test_PatternModel> test_Pattern = Test_PatternModel.getTest_Pattern(id);
                    for (int i = 0; i < test_Pattern.ToArray().Length; i++)
                    {
                        tong_so_cau++;
                    }
                    @ViewBag.tong_so_cau = tong_so_cau;
                }
                return View(ts);
            }
            catch { return RedirectToAction("Home"); }
        }
        public ActionResult Detail2(int id)
        {
            try
            {
                ViewBag.menu = xulymenu();
                Test_ServiceModel ts = Test_ServiceModel.getTestAll().Find(delegate(Test_ServiceModel s) { return s.id == id.ToString(); });
                Session["thoi_gian"] = ts.thoi_gian;
                Session["is_pattern"] = ts.is_pattern;

                int tong_so_cau = 0;
                if (ts.is_pattern == "0")
                {
                    List<Test_QuestionDetailModel> test_QuestionDetail = Test_QuestionDetailModel.getTest_QuestionDetail(id.ToString());
                    for (int i = 0; i < test_QuestionDetail.ToArray().Length; i++)
                    {
                        tong_so_cau += Convert.ToInt32(test_QuestionDetail[i].so_cau);
                    }
                    @ViewBag.tong_so_cau = tong_so_cau;
                }
                else
                {
                    TracNghiem.Areas.Admin.Models.Test_PatternModel Test_PatternModel = new TracNghiem.Areas.Admin.Models.Test_PatternModel();
                    List<TracNghiem.Areas.Admin.Models.Test_PatternModel> test_Pattern = Test_PatternModel.getTest_Pattern(id);
                    for (int i = 0; i < test_Pattern.ToArray().Length; i++)
                    {
                        tong_so_cau++;
                    }
                    @ViewBag.tong_so_cau = tong_so_cau;
                }
                return View("Detail",ts);
            }
            catch { return RedirectToAction("Home"); }
        }
        Test_QuestionModel Test_QuestionModel = new Test_QuestionModel();   
        public ActionResult Test_Start(int id)
        {
            if (Session["is_pattern"] != null)
            {
                try
                {
                    string de_thi_id = id.ToString();
                    if (Session["user_id"] != null)
                    {
                        string user_id = Session["user_id"].ToString();

                        if (BaiThiModel.checkUser_Baithi(user_id, de_thi_id) > 0)
                        {
                            ViewBag.checktest = "ok";
                        }
                    }
                    ViewBag.menu = xulymenu();
                    List<Test_QuestionModel> ts_global = new List<Models.Test_QuestionModel>();                    
                    if (Session["is_pattern"].ToString() == "0")
                    {
                        List<Test_QuestionDetailModel> ts_detail = Test_QuestionDetailModel.getTest_QuestionDetail(id.ToString());

                        string[] phanloai_id = new string[ts_detail.ToArray().Length];
                        string[] so_cau = new string[ts_detail.ToArray().Length];
                        int i = 0;
                        foreach (var item in ts_detail)
                        {
                            //de_thi_id = item.de_thi_id;
                            phanloai_id[i] = item.phanloai_id;
                            so_cau[i] = item.so_cau;
                            i++;
                        }
                        ts_global = Test_QuestionModel.getQuestionRandom(de_thi_id, phanloai_id, so_cau);
                        Session["start_sevice"] = ts_global;
                        @ViewBag.thoi_gian = Session["thoi_gian"];
                        return View(ts_global);
                    }
                    else
                    {
                        ts_global = Test_QuestionModel.getQuestionRandom_Dethi_Pattern(de_thi_id);
                        Session["start_sevice"] = ts_global;
                        @ViewBag.thoi_gian = Session["thoi_gian"];
                        return View(ts_global);
                    }
                }
                catch { return RedirectToAction("Home"); }
            }
            else
                return RedirectToAction("Home");
        }
        [HttpPost]
        public ActionResult Test_Start(Test_QuestionModel ts)
        {
            if (Session["is_pattern"] != null)
            {
                try
                {
                    ViewBag.menu = xulymenu();
                    int k = 1;
                    var myList = (List<Test_QuestionModel>)Session["start_sevice"];
                    foreach (var item in myList)
                    {
                        if (Request.Form["cb" + k] == null || string.IsNullOrWhiteSpace(Request.Form["cb" + k]))
                            item.status_user = "0";
                        else
                            item.status_user = "1";
                        k = k + 1;
                    }
                    Session["start_sevice"] = myList;
                    return RedirectToAction("Test_Result", "Test_Service");
                }
                catch { return RedirectToAction("Home"); }
            }
            else
                return RedirectToAction("Home");

        }
        BaiThiModel BaiThiModel = new BaiThiModel();
        public ActionResult Test_Result()
        {
            if (Session["is_pattern"] != null)
            {
                try
                {
                    ViewBag.download = "";
                    ViewBag.menu = xulymenu();
                    int k = 0;
                    int j = 0;
                    string trang_thai = "1";
                    var ts_global = (List<Test_QuestionModel>)Session["start_sevice"];
                    do
                    {
                        if (ts_global[k].id == ts_global[k + 1].id)
                        {
                            j++;
                            if (ts_global[k].status_user != ts_global[k].trangthai_tl)
                                trang_thai = "0";
                            for (int i = k - j + 1; i < k + 1; i++)
                                ts_global[i].kq = trang_thai;
                        }
                        else
                        {
                            if (ts_global[k].status_user != ts_global[k].trangthai_tl)
                                trang_thai = "0";
                            for (int i = k - j; i < k + 1; i++)
                                ts_global[i].kq = trang_thai;
                            trang_thai = "1";
                            j = 0;
                        }
                        if (k == ts_global.ToArray().Length - 2)
                        {
                            if (ts_global[k + 1].status_user != ts_global[k + 1].trangthai_tl)
                                trang_thai = "0";
                            for (int i = k + 1 - j; i < k + 1; i++)
                                ts_global[i].kq = trang_thai;
                        }
                        k++;
                    }
                    while (k < ts_global.ToArray().Length - 1);
                    try
                    { 
                       
                        if (Session["user_id"]!=null)
                        {
                            //BaiThiModel bt = new BaiThiModel();
                            //bt.user_id = Session["user_id"].ToString();
                            //string lan_thi = bt.getLan_thi(ts_global[0].de_thi_id, bt.user_id);
                            //for (int i = 0; i < ts_global.ToArray().Length; i++)
                            //{
                            //    bt.de_thi_id = ts_global[i].de_thi_id;
                            //    bt.cau_tl_id = ts_global[i].cau_tl_id;
                            //    bt.user_status = ts_global[i].status_user;
                            //    bt.lan_thi = lan_thi;
                            //    bt.ngay = DateTime.Now.ToString("dd/MM/yyyy");
                            //    BaiThiModel.addBai_Thi(bt);
                            //}

                            BaiThiModel bt = new BaiThiModel();
                            string user_id = Session["user_id"].ToString();
                            string lan_thi = bt.getLan_thi(ts_global[0].de_thi_id, user_id);
                            string de_thi_id = ts_global[0].de_thi_id;
                            string ngay = DateTime.Now.ToString("dd/MM/yyyy");
                            string[] cau_tl_id_array = new string[ts_global.ToArray().Length];
                            string[] user_status_array = new string[ts_global.ToArray().Length];
                            for (int i = 0; i < ts_global.ToArray().Length; i++)
                            {
                                cau_tl_id_array[i] = ts_global[i].cau_tl_id;
                                user_status_array[i] = ts_global[i].status_user;
                            }                           
                            

                            Test_ServiceModel ts = Test_ServiceModel.getTestAll().Find(delegate(Test_ServiceModel s) { return s.id == de_thi_id.ToString(); });
                            if (ts.is_test == "1")
                            {
                                if (BaiThiModel.checkUser_Baithi(user_id, de_thi_id) <= 0)
                                {
                                    ViewBag.download = "ok";
                                }
                                BaiThiModel.addBai_Thi(user_id, lan_thi, de_thi_id, ngay, cau_tl_id_array, user_status_array);
                                Session["message"] = "<h3 align='center'><font color='red'>Chúc mừng <span style='text-transform:uppercase'>" + Session["user_name"] + "</span> đã hoàn thành bài kiểm tra, kết quả đã được lưu!</font></h3>";
                            }
                                    
                        }
                    }
                    catch { }
                    if (Session["message"]!=null)
                        ViewBag.message = Session["message"];
                    else
                        ViewBag.message = "";
                    Session["start_sevice"] = null;
                    Session["is_pattern"] = null;
                    Session["thoi_gian"] = null;
                    Session["message"] = null;
                    return View(ts_global);
                }
                catch { return RedirectToAction("Home"); }
            }
            else
                return RedirectToAction("Home");
        }
        public  string xulymenu()
        {
            UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
            //
            List<string> kq = new List<string>();
            TracNghiem.Areas.Admin.Models.DichvuModel dichvu = new TracNghiem.Areas.Admin.Models.DichvuModel();
            TracNghiem.Areas.Admin.Models.Bai_VietModels baiviet = new TracNghiem.Areas.Admin.Models.Bai_VietModels();
            string htmlmenu = "";
            //lấy danh mục cha
            List<TracNghiem.Areas.Admin.Models.DichvuModel> dv = dichvu.getDichvu_byid2(0, 1);//nếu xuất hiện các mục khác thì thay 1=0

            foreach (TracNghiem.Areas.Admin.Models.DichvuModel a in dv)
            {
                //lấy danh mục con của danh mục cha
                List<TracNghiem.Areas.Admin.Models.DichvuModel> dvc = dichvu.getDichvu_byid2(int.Parse(a.id),0);

                //không lấy danh mục con nữa -- theo ý của trang 
                //if (dvc.Count > 0)
                //{
                //    htmlmenu += "<li class=\"parent first\"><a class=\"collapsed\"  >" + a.name + "</a>";
                //    htmlmenu += "<ul style='display: none;' id='uldvuinternet'>";
                //    foreach (var b in dvc)
                //    {
                //       // htmlmenu += "<li><a href='/tracnghiem/Test_Service/index/" + b.id + "' >" + b.name + "</a></li>";
                //        //them bai viet
                //        htmlmenu += "<li><a href='" + u.Action("index", "Test_Service", new { id = b.id }) + "'>" + b.name + "</a></li>";
                //    }
                //    htmlmenu += "</ul></li>";
                //}

                //else {

                    if (int.Parse(a.group_id) == 1)
                        {
                    htmlmenu += "<li class=\"parent first\"><a href='" + u.Action("index", "Test_Service", new { id = a.id }) + "'>" + a.name + "</a>";
                        }
                    else
                    {
                        htmlmenu += "<li class=\"parent\"><a href='" + u.Action("index", "Test_Service", new { id = a.id }) + "'><font color=#00a1de>" + a.name + "</font></a>";
                    }

                //}
            }
            htmlmenu += "<li class=\"parent first\"><a href='" + u.Action("index2", "Test_Service") + "'><font color='green'>Kiểm tra tổng hợp</font></a>";
            return htmlmenu;

        }
       

    }
}
